package com.fwmagic.rpc.handler;

import com.fwmagic.rpc.service.pojo.RpcRequest;
import com.fwmagic.rpc.transport.RpcNetTransport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.Socket;

public class MyInvocationHandler implements InvocationHandler {

    private String host;

    private Integer port;

    public MyInvocationHandler() {
    }

    public MyInvocationHandler(String host, Integer port) {
        this.host = host;
        this.port = port;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Socket socket = null;
        Object object = null;

        try {
            //获取要调用的类，方法，参数
            RpcRequest rpcRequest = new RpcRequest();
            rpcRequest.setMethodName(method.getName());
            rpcRequest.setArgs4Method(args);
            //为了鉴别方法的重载，这里需要传入参数类型
            rpcRequest.setParamTypes(method.getParameterTypes());

            //传输类
            RpcNetTransport rpcNetTransport = new RpcNetTransport(host, port);
            //建立远程连接
            socket = rpcNetTransport.newSocket();
            //请求远程服务，发送数据，获取执行结果
            object = rpcNetTransport.sendRequest(socket,rpcRequest);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null) socket.close();
        }
        return object;
    }
}
